# -*- coding: utf-8 -*-
import json
import os
from time import sleep
import filetype
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QDockWidget, QAction, QFileDialog
import cv2.cv2 as cv2
import copy
from imageManager import *

PARA_PATH = os.path.dirname(__file__)

PIC_INDEX = 0


class videoDevGui(QtWidgets.QWidget):
    update_para_signal = QtCore.pyqtSignal(int, dict)
    img_type = ["bmp", "jpg", "gif", "png", "jpeg"]
    index = 0
    capture = None

    def __init__(self, parent=None):
        super(videoDevGui, self).__init__(parent)
        self.imgMat = None
        self.filedir = ''
        self.filename = []
        self.img_index = 0
        self.func_name = ""
        parafile = os.path.join(PARA_PATH, "device_para.json")
        with open(parafile, "r", encoding='utf-8') as f:
            self.para_list = json.loads(f.read())

    def setPara(self, index, para):
        self.index = index
        if para is not None:
            self.para_list = para
            self.filedir = self.para_list["filedir"]
            self.filename = self.para_list["filename"]
            self.savePathLineEdit.setText(self.filedir)
            self.capture = cv2.VideoCapture(self.filename)

    def setFunctionName(self, name):
        self.func_name = name

    def setImg(self, img):
        self.imgMat = copy.deepcopy(img)

    def initUI(self):
        openLabel = QtWidgets.QLabel(self)
        openLabel.setText("name:")
        self.savePathLineEdit = QtWidgets.QLineEdit(self)
        browebtn = QtWidgets.QPushButton(self)
        browebtn.setText("browse")

        hbox1 = QtWidgets.QHBoxLayout()
        hbox1.addWidget(openLabel)
        hbox1.addWidget(self.savePathLineEdit)
        hbox1.addWidget(browebtn)

        browebtn.clicked.connect(self.browebtn_clicked)

        btn_open = QtWidgets.QPushButton(self)
        btn_open.setText("open")
        btn_open.clicked.connect(self.btn_open_clicked)

        btn_next = QtWidgets.QPushButton(self)
        btn_next.setText("next")
        btn_next.clicked.connect(self.btn_next_clicked)

        hbox2 = QtWidgets.QHBoxLayout()
        hbox2.addWidget(btn_open)
        hbox2.addWidget(btn_next)

        btn_ok = QtWidgets.QPushButton(self)
        btn_ok.setText("ok")
        btn_ok.clicked.connect(self.btn_ok_clicked)

        btn_cancel = QtWidgets.QPushButton(self)
        btn_cancel.setText("cancel")
        btn_cancel.clicked.connect(self.btn_cancel_clicked)

        hbox3 = QtWidgets.QHBoxLayout()
        hbox3.addWidget(btn_ok)
        hbox3.addWidget(btn_cancel)

        vbox = QtWidgets.QVBoxLayout()
        vbox.addLayout(hbox1)
        vbox.addLayout(hbox2)
        vbox.addStretch(12)
        vbox.addLayout(hbox3)

        self.setLayout(vbox)

    def browebtn_clicked(self):
        filename = QFileDialog.getOpenFileName(self, "Open file", "..", "Video files(*.mp4 *.mkv *.avi)")
        if filename[0]:
            self.filename = filename[0]
            self.savePathLineEdit.setText(self.filename)

    def btn_next_clicked(self):
        if self.capture is None:
            return
        frame_num = self.capture.get(cv2.CAP_PROP_POS_FRAMES)
        self.capture.set(cv2.CAP_PROP_POS_FRAMES, self.index)
        if self.index < frame_num:
            self.index += 1
        ret, frame = self.capture.read()
        if ret:
            img_mng.img = frame
            self.imgMat = copy.deepcopy(img_mng.img)
            img_mng.dispImg(self.imgMat)
            img_mng.setOriginMat(self.imgMat)

    def btn_open_clicked(self):
        if self.filename is None:
            return
        self.capture = cv2.VideoCapture(self.filename)

    def btn_ok_clicked(self):
        pj_dir = os.path.split(self.filename)
        self.para_list["filedir"] = pj_dir[0]
        self.para_list["filename"] = self.filename
        self.update_para_signal.emit(self.index, self.para_list)
        parafile = os.path.join(PARA_PATH, "device_para.json")
        with open(parafile, "w", encoding='utf-8') as f:
            f.write(json.dumps(self.para_list, indent=4))

    def btn_cancel_clicked(self):
        self.close()

    def run(self, para):
        global PIC_INDEX
        filedir = para["filedir"]
        filename = para["filename"]
        if filedir == '':
            return
        if filename is None:
            return
        frame_num = self.capture.get(cv2.CAP_PROP_POS_FRAMES)
        self.capture.set(cv2.CAP_PROP_POS_FRAMES, self.index)
        if self.index < frame_num:
            self.index += 1
        ret, frame = self.capture.read()
        if ret:
            self.imgMat = frame
            img_mng.setOriginMat(self.imgMat)
            img_mng.dispImg(self.imgMat)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    ui = videoDevGui()
    ui.initUI()
    ui.show()
    sys.exit(app.exec_())
